<template>
    <div class="wrapper">
        <!-- header部分 -->
        <header>
            <div class="icon-location-box">
                <div class="icon-location"></div>
            </div>
            <div class="location-text" @click="gotoAddress">
                {{ addressText }}
                <i class="fa fa-caret-down"></i>
            </div>
        </header>

        <!-- search部分（滚动吸顶） -->
        <div class="search">
            <div class="search-fixed-top" ref="fixedBox" :class="{ fixed: isFixed }">
                <div class="search-box-wrapper">
                    <input class="search-box" type="text" placeholder="搜索饿了么商家、商品名称" 
                    v-model="searchQuery" 
                    @keyup.enter="toSearchResults"/>
                    <button class="search-btn" @click="toSearchResults">
                        <i class="fa fa-search"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- 点餐分类（Swiper 翻页） -->
        <div class="foodtype-swiper">
            <Swiper :slides-per-view="1" :modules="[Pagination]" :pagination="{ clickable: true }"
                style="width: 100vw; height: 48vw;">
                <SwiperSlide v-for="(page, idx) in foodTypePages" :key="idx">
                    <ul class="foodtype">
                        <li v-for="(item, i) in page" :key="i" @click="item && toBusinessList(item.id)">
                            <template v-if="item">
                                <img :src="item.img" />
                                <p>{{ item.label }}</p>
                            </template>
                        </li>
                    </ul>
                </SwiperSlide>
            </Swiper>
        </div>

        <!-- 横幅广告部分 -->
        <div class="banner">
            <h3>品质套餐</h3>
            <p>搭配齐全吃得好</p>
            <a>立即抢购 &gt;</a>
        </div>

        <!-- 超级会员部分 -->
        <div class="supermember">
            <div class="left">
                <img src="../assets/super_member.png" />
                <h3>超级会员</h3>
                <p>&#8226; 每月享超值权益</p>
            </div>
            <div class="right">立即开通 &gt;</div>
        </div>

        <!-- 推荐商家标题 -->
        <div class="recommend">
            <div class="recommend-line"></div>
            <p>推荐商家</p>
            <div class="recommend-line"></div>
        </div>

        <!-- 推荐方式 -->
        <ul class="recommendtype">
            <li v-for="type in sortTypes" :key="type.value" :class="{ active: recommendType === type.value }"
                @click="selectType(type.value)">
                {{ type.label }}
                <i v-if="type.value === recommendType" @click.stop="toggleSortManner"
                    :class="sortManner === 'asc' ? 'fa fa-caret-down' : 'fa fa-caret-up'" />
            </li>
            <li @click="showFilter = true">筛选<i class="fa fa-filter"></i></li>
        </ul>

        <!-- 筛选弹层 -->
        <div v-if="showFilter" class="filter-popup">
            <div class="filter-content">
                <h3 style="padding: 2vw 3vw;">筛选条件</h3>
                <div class="filter-options" style="padding: 0 3vw 3vw;">
                    <!-- 分类筛选 -->
                    <div class="filter-group">
                        <label class="filter-label">分类：</label>
                        <label class="checkbox-label" v-for="(label, number) in categoryOptionsMap" :key="number">
                            <input type="checkbox" :value="Number(number)" v-model.number="filterCategories" />
                            <span>{{ label }}</span>
                        </label>
                    </div>
                    <!-- 价格区间 -->
                    <div class="filter-group">
                        <label class="filter-label">价格区间：</label>
                        <input type="number" v-model="filterMinPrice" placeholder="最低价" style="width: 8vw;" />
                        -
                        <input type="number" v-model="filterMaxPrice" placeholder="最高价" style="width: 8vw;" />
                    </div>
                    <div class="filter-botton">
                        <button @click="clearFilter">清空</button>
                        <button @click="applyFilter">查看</button>
                    </div>
                </div>
            </div>
            <div class="filter-blank" @click="showFilter = false"></div>
        </div>

        <!-- 推荐商家列表 -->
        <ul class="business">
            <li v-for="b in sortedBusinessList" :key="b.businessId" class="business-item"
                @click="toBusinessDetail(b.businessId)">
                <img :src="b.businessImg" alt="商家图片" class="business-img" />
                <div class="business-info">
                    <div class="business-info-h">
                        <h3>{{ b.businessName }}</h3>
                        <span class="business-order-quantity" v-if="b.orderCount">订单数：{{ b.orderCount }}</span>
                    </div>
                    <div class="business-info-star">
                        <span class="star-group">
                            <i v-for="n in 5" :key="n" class="fa fa-star"
                                :class="{ active: n <= Math.round(b.rating || 0) }"></i>
                        </span>
                        <span class="business-rating">{{ (b.rating || 0).toFixed(1) }}</span>
                        <span class="business-sales">月售{{ b.sales || 0 }}单</span>
                    </div>
                    <div class="business-info-delivery">
                        <span>&#165;{{ b.startPrice }}起送 | &#165;{{ b.deliveryPrice }}配送</span>
                    </div>
                    <div class="business-info-explain">
                        <span>{{ b.businessExplain }}</span>
                    </div>
                    <div class="business-info-position">
                        <i class="fa fa-location-arrow"></i>
                        <span>{{ b.businessAddress }}</span>
                    </div>
                </div>
            </li>
        </ul>

        <!-- 底部菜单部分 -->
        <Footer />
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import Footer from '../components/Footer.vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/pagination'
import { Pagination } from 'swiper/modules'

// 搜索输入
const searchQuery = ref('')

// 路由
const router = useRouter()

// 吸顶控制
const fixedBox = ref(null)
const isFixed = ref(false)
const handleScroll = () => {
    const width = document.documentElement.clientWidth
    const scroll = window.scrollY || document.documentElement.scrollTop
    isFixed.value = scroll > width * 0.12
}

// 地址展示（从 sessionStorage 获取）
const addressText = computed(() => {
    const user = sessionStorage.getItem('user')
    if (!user) return '请选择送货地址'
    // 你的项目如有更复杂的地址存储逻辑，可在此处替换
    const addr = sessionStorage.getItem('address')
    return addr || '请选择送货地址'
})

// 分类数据（沿用你已有 10 个图标）
const foodTypeList = [
    { id: 1, img: require('../assets/dcfl09.png'), label: '中餐' },
    { id: 2, img: require('../assets/dcfl04.png'), label: '快餐' },
    { id: 3, img: require('../assets/dcfl08.png'), label: '韩餐' },
    { id: 4, img: require('../assets/烧烤-烤串.png'), label: '烧烤' },
    { id: 5, img: require('../assets/dcfl05.png'), label: '饮品' },
    { id: 6, img: require('../assets/dcfl12.png'), label: '火锅' },
    { id: 7, img: require('../assets/中餐-剁椒鱼头.png'), label: '川菜' },
    { id: 8, img: require('../assets/dcfl08.png'), label: '湘菜' },
    { id: 9, img: require('../assets/中餐-龙井虾仁.png'), label: '粤菜' },
    { id: 10, img: require('../assets/中餐-九转大肠.png'), label: '东北菜' },
    { id: 11, img: require('../assets/icons8-食品和葡萄酒-100.png'), label: '西餐' },
    { id: 12, img: require('../assets/icons8-美食-85.png'), label: '日料' },
    { id: 13, img: require('../assets/icons8-素食食品-50.png'), label: '轻食沙拉' },
    { id: 14, img: require('../assets/素食.jpg'), label: '素食' },
    { id: 15, img: require('../assets/icons8-美食-64.png'), label: '面包甜点' },
]

// 分页（每页 10 个）
const pageSize = 10
const foodTypePages = computed(() => {
    const pages = []
    for (let i = 0; i < foodTypeList.length; i += pageSize) {
        const page = foodTypeList.slice(i, i + pageSize)
        while (page.length < pageSize) page.push(null)
        pages.push(page)
    }
    return pages
})

// 推荐/筛选状态
const showFilter = ref(false)
const recommendType = ref(1) // 1: 综合排序  2: 销量最高
const sortManner = ref('asc') // asc/desc

const filterCategories = ref([])
const filterMinPrice = ref('')
const filterMaxPrice = ref('')

// 分类可选项（示例，可按需扩展/替换）
const categoryOptionsMap = {
    1: '美食',
    2: '早餐',
    3: '跑腿代购',
    4: '汉堡披萨',
    5: '甜品饮品',
    6: '速食简餐',
    7: '地方小吃',
    8: '米粉面馆',
    9: '中式简餐',
    10: '炸鸡炸串'
}

const businessList = ref([
    {
        businessId: 16,
        businessImg: require('../assets/sj01.png'),
        businessName: '万家饺子（软件园E18店）',
        rating: 4.9,
        sales: 345,
        startPrice: 15,
        deliveryPrice: 3,
        businessExplain: '各种饺子',
        businessAddress: '沈阳市 软件园E18'
    },
    {
        businessId: 17,
        businessImg: require('../assets/sj02.png'),
        businessName: '小锅饭豆腐馆（全运店）',
        rating: 4.8,
        sales: 280,
        startPrice: 15,
        deliveryPrice: 3,
        businessExplain: '家常小炒',
        businessAddress: '沈阳市 全运路'
    },
    {
        businessId: 18,
        businessImg: require('../assets/sj03.png'),
        businessName: '麦当劳麦乐送（全运路店）',
        rating: 4.7,
        sales: 500,
        startPrice: 15,
        deliveryPrice: 3,
        businessExplain: '汉堡薯条',
        businessAddress: '沈阳市 全运路'
    },
    {
        businessId: 19,
        businessImg: require('../assets/sj04.png'),
        businessName: '米村拌饭（浑南店）',
        rating: 4.9,
        sales: 320,
        startPrice: 15,
        deliveryPrice: 3,
        businessExplain: '拌饭套餐',
        businessAddress: '沈阳市 浑南'
    }
])

// 统计每个商家的订单数（如无接口可忽略）
async function fetchOrderCounts() {
    try {
        const ids = businessList.value.map(b => b.businessId)
        const countMap = {}
        const tasks = ids.map(id =>
            axios.get(`/orders/public/by-business/${id}/count`)
                .then(res => {
                    const n = res.data?.data?.count
                    countMap[id] = Number.isFinite(n) ? n : 0
                })
                .catch(() => { countMap[id] = 0 })
        )
        await Promise.all(tasks)
        businessList.value.forEach(b => { b.orderCount = countMap[b.businessId] || 0 })
    } catch { /* ignore */ }
}

// 获取月售和评分（如无接口可忽略）
async function fetchBusinessExtraInfo() {
    for (const b of businessList.value) {
        try {
            const orderRes = await axios.get('/orders/business', { params: { businessId: b.businessId } })
            const orders = orderRes.data || []
            const now = new Date()
            const m = now.getMonth()
            b.sales = orders.filter(o => new Date(o.orderTime).getMonth() === m).length
        } catch (e) {
            // ignore
        }
        try {
            const commentRes = await axios.get(`/comments/business/${b.businessId}`)
            const comments = commentRes.data || []
            b.rating = comments.length ? comments.reduce((s, c) => s + (c.rating || 0), 0) / comments.length : 0
        } catch (e) {
            // ignore
        }
    }
}

// 过滤、排序
const filteredBusinessList = computed(() => {
    let list = [...businessList.value]
    if (filterCategories.value.length > 0) {
        list = list.filter(b => filterCategories.value.includes(b.businessType))
    }
    if (filterMinPrice.value !== '') {
        list = list.filter(b => b.startPrice >= Number(filterMinPrice.value))
    }
    if (filterMaxPrice.value !== '') {
        list = list.filter(b => b.startPrice <= Number(filterMaxPrice.value))
    }
    return list
})

const sortedBusinessList = computed(() => {
    const list = [...filteredBusinessList.value]
    if (recommendType.value === 2) {
        list.sort((a, b) => (sortManner.value === 'asc' ? a.sales - b.sales : b.sales - a.sales))
    }
    return list
})

// 交互
function selectType(type) {
    recommendType.value = type
}
function toggleSortManner() {
    sortManner.value = sortManner.value === 'asc' ? 'desc' : 'asc'
}
function clearFilter() {
    filterCategories.value = []
    filterMinPrice.value = ''
    filterMaxPrice.value = ''
}
function applyFilter() {
    showFilter.value = false
}

function toBusinessList(orderTypeId) {
    router.push({ path: '/businessList', query: { orderTypeId } })
}

function toSearchResults() {
    router.push({ path: '/businessSearch', query: { keyword: searchQuery.value } })
}

function toBusinessDetail(businessId) {
    router.push({ path: '/businessInfo', query: { businessId } })
}

function gotoAddress() {
    router.push('/userAddress')
}

onMounted(() => {
    window.addEventListener('scroll', handleScroll)
    // 可选：尝试获取扩展信息
    fetchOrderCounts()
    //fetchBusinessExtraInfo()
})
onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
    width: 100%;
    height: 100%;
}

/****************** header ******************/
.wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    display: flex;
    align-items: center;
}

.wrapper header .icon-location-box {
    width: 3.5vw;
    height: 3.5vw;
    margin: 0 1vw 0 3vw;
}

.wrapper header .location-text {
    font-size: 4.5vw;
    font-weight: 700;
    color: #fff;
    cursor: pointer;
}

.wrapper header .location-text .fa-caret-down {
    margin-left: 1vw;
}

/****************** search ******************/
.wrapper .search {
    width: 100%;
    height: 13vw;
    border-radius: 1vw;
}

.wrapper .search .search-fixed-top {
    width: 100%;
    height: 13vw;
    background-color: #0097FF;
    display: flex;
    justify-content: center;
    align-items: center;
}

.search-fixed-top.fixed {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
}

.wrapper .search .search-fixed-top .search-box-wrapper {
    width: 90%;
    height: 8vw;
    background-color: #fff;
    border-radius: 4vw;
    display: flex;
    align-items: center;
    box-shadow: 0 0 2vw #eee;
    padding: 0 2vw;
}

.wrapper .search .search-fixed-top .search-box-wrapper .search-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 0 1vw;
    display: flex;
    align-items: center;
}

.wrapper .search .search-fixed-top .search-box-wrapper .fa-search {
    font-size: 3.5vw;
    color: #0097FF;
}

.wrapper .search .search-fixed-top .search-box-wrapper .search-box {
    flex: 1;
    height: 100%;
    border: none;
    outline: none;
    font-size: 3.5vw;
    color: #AEAEAE;
    background: transparent;
}

/****************** 点餐分类（Swiper 每页 10 个） ******************/
.foodtype-swiper {
    width: 100vw;
    height: 48vw;
    margin-bottom: 2vw;
}

.foodtype {
    width: 100vw;
    height: 48vw;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-content: center;
    margin: 0;
    padding: 0;
}

.foodtype li {
    width: 18vw;
    height: 20vw;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    user-select: none;
    cursor: pointer;
    margin-bottom: 2vw;
}

.foodtype li img {
    width: 12vw;
    height: 10.3vw;
}

.foodtype li p {
    font-size: 3.2vw;
    color: #666;
}

/****************** 横幅广告部分 ******************/
.wrapper .banner {
    width: 95%;
    margin: 0 auto;
    height: 29vw;
    background-image: url(../assets/index_banner.png);
    background-repeat: no-repeat;
    background-size: cover;
    box-sizing: border-box;
    padding: 2vw 6vw;
}

.wrapper .banner h3 {
    font-size: 4.2vw;
    margin-bottom: 1.2vw;
}

.wrapper .banner p {
    font-size: 3.4vw;
    color: #666;
    margin-bottom: 2.4vw;
}

.wrapper .banner a {
    font-size: 3vw;
    color: #C79060;
    font-weight: 700;
}

/****************** 超级会员部分 ******************/
.wrapper .supermember {
    width: 95%;
    margin: 0 auto;
    height: 11.5vw;
    background-color: #FEEDC1;
    margin-top: 1.3vw;
    border-radius: 2px;
    color: #644F1B;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #ccc;
}

.wrapper .supermember .left {
    display: flex;
    align-items: center;
    margin-left: 4vw;
    user-select: none;
}

.wrapper .supermember .left img {
    width: 6vw;
    height: 6vw;
    margin-right: 2vw;
}

.wrapper .supermember .left h3 {
    font-size: 4vw;
    margin-right: 2vw;
}

.wrapper .supermember .left p {
    font-size: 3vw;
}

.wrapper .supermember .right {
    font-size: 3vw;
    margin-right: 4vw;
    cursor: pointer;
}

/****************** 推荐商家标题 ******************/
.wrapper .recommend {
    width: 100%;
    height: 14vw;
    display: flex;
    justify-content: center;
    align-items: center;
}

.wrapper .recommend .recommend-line {
    width: 6vw;
    height: 0.2vw;
    background-color: #888;
}

.wrapper .recommend p {
    font-size: 4vw;
    margin: 0 4vw;
}

/****************** 推荐方式 ******************/
.wrapper .recommendtype {
    width: 100%;
    height: 5vw;
    margin-bottom: 5vw;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.recommendtype .active {
    color: #0097FF;
    font-weight: bold;
    border-bottom: 2px solid #0097FF;
}

.wrapper .recommendtype li {
    font-size: 3.5vw;
    color: #555;
}

/****************** 筛选弹层 ******************/
.filter-popup {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    background: rgba(0, 0, 0, 0.3);
}

.filter-content {
    flex: 1;
    width: 100vw;
    background: #fff;
    border-radius: 2vw 2vw 0 0;
    box-shadow: 0 2vw 4vw #eee;
    margin-top: 0;
    animation: slideDown 0.3s;
}

.filter-blank {
    flex: 1;
    background: rgba(0, 0, 0, 0.3);
}

@keyframes slideDown {
    from {
        transform: translateY(-100%);
    }

    to {
        transform: translateY(0);
    }
}

.filter-group {
    margin-bottom: 2vw;
    display: flex;
    align-items: center;
    font-size: 3vw;
    flex-wrap: wrap;
}

.filter-label {
    width: 18vw;
    font-weight: bold;
    color: #333;
}

.filter-botton {
    display: flex;
    justify-content: flex-end;
    gap: 2vw;
    margin-top: 3vw;
}

.filter-botton button {
    padding: 1vw 4vw;
    font-size: 3vw;
    border-radius: 1vw;
    border: none;
    background: #0097FF;
    color: #fff;
    cursor: pointer;
}

.checkbox-label {
    display: flex;
    align-items: center;
    padding: 0.5vw 2vw;
    border: 1px solid #ccc;
    border-radius: 2vw;
    margin: 1vw 2vw 1vw 0;
    font-size: 3vw;
    cursor: pointer;
    background: #fff;
    user-select: none;
}

.checkbox-label input[type='checkbox'] {
    margin-right: 1vw;
    width: 3vw;
    height: 3vw;
}

/****************** 推荐商家列表 ******************/
.business {
    width: 100%;
    margin-bottom: 14vw;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-bottom: 16vw;
}

.business-item {
    height: 37vw;
    width: 95%;
    box-sizing: border-box;
    padding: 2vw;
    user-select: none;
    border: solid 1px #DDD;
    border-radius: 32px;
    display: flex;
    cursor: pointer;
    margin: 0 0 4vw 0;
    align-items: center;
    background: #fff;
    transition: box-shadow 0.2s, border-color 0.2s;
}

.business-item:hover {
    box-shadow: 0 4px 16px rgba(0, 151, 255, 0.08);
    border-color: #0097FF;
}

.business-img {
    width: 30vw;
    height: 30vw;
    min-width: 30vw;
    min-height: 30vw;
    border-radius: 2vw;
    object-fit: cover;
    background: #eee;
}

.business-info {
    width: 90%;
    box-sizing: border-box;
    padding-left: 3vw;
    font-size: 4vw;
}

.business-info-h {
    font-size: 3.5vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2vw;
}

.business-info-h h3 {
    color: #333;
    font-weight: 600;
    margin: 0;
}

.business-order-quantity {
    font-size: 2.8vw;
    color: #0097FF;
    background: #e6f2ff;
    border-radius: 1vw;
    padding: 0.2vw 1vw;
    margin-left: 2vw;
}

.business-info-star {
    display: flex;
    align-items: center;
    font-size: 3.1vw;
    margin-bottom: 2vw;
    gap: 1vw;
}

.star-group {
    display: flex;
}

.fa-star {
    color: #ccc;
    margin-right: 0.5vw;
}

.fa-star.active {
    color: #FEC80E;
}

.business-rating {
    color: #FEC80E;
    font-weight: bold;
    margin-left: 1vw;
}

.business-sales {
    color: #666;
    margin-left: 2vw;
}

.business-info-delivery {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #666;
    font-size: 3.1vw;
    margin-bottom: 2vw;
}

.business-info-explain {
    color: #666;
    font-size: 2.8vw;
    margin-bottom: 3vw;
}

.business-info-position {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 3vw;
}

.business-info-position .fa-location-arrow {
    margin-right: 1vw;
    color: #70BC46;
}
</style>